package com.example.a17376080_dlz_finaltest;

import android.annotation.SuppressLint;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import utils.HttpUtil;
import utils.MyNetCall;

@SuppressLint("NewApi")
public class ReleaseActivity extends AppCompatActivity implements View.OnClickListener {
    private ProgressDialog prgDialog;
    ImageView chioose_image;
    private int RESULT_LOAD_IMG = 1;
    private RequestParams params = new RequestParams();
    private String encodedString;
    private Bitmap bitmap;
    private String imgPath;
    TextView tv_fb;
    EditText editTextName;
    String content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release);
        initView();
    }

    private void initView() {
        chioose_image=findViewById(R.id.chioose_image);
        tv_fb=findViewById(R.id.tv_fb);
        editTextName=findViewById(R.id.editTextName);
        chioose_image.setOnClickListener(this);
        tv_fb.setOnClickListener(this);
        editTextName.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.chioose_image:
                loadImage();
                break;
            case R.id.tv_fb:
                uploadImage();
                startNotify();
                this.finish();
                break;
                default:
                    break;
        }
    }

    private void startNotify() {
        Intent intent=new Intent(this,World_Fragment.class);
        PendingIntent pi=PendingIntent.getActivities(this,0, new Intent[]{intent},0);
        SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
        NotificationManager manage= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification=new NotificationCompat.Builder(this)
                .setContentTitle(sp.getString("currentUsername","")+"发布了一条消息")
                .setContentText("点击查看消息")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                        R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .setAutoCancel(true)
                .build();
        manage.notify(1,notification);
    }


    private void loadImage() {
        Toast.makeText(this,"点击了",Toast.LENGTH_LONG).show();
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }
    //当图片被选中的返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // 获取游标
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.imageView);
                imgView.setImageBitmap(BitmapFactory.decodeFile(imgPath));
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
        }
    }
    //开始上传图片
    private void uploadImage() {
        if (imgPath != null && !imgPath.isEmpty()) {
           // prgDialog.setMessage("Converting Image to Binary Data");
            Log.d("准备上传", "uploadImage: ");
            //prgDialog.show();
            encodeImagetoString();
        } else {
            Toast.makeText(getApplicationContext(), "You must select image from gallery before you try to upload",
                    Toast.LENGTH_LONG).show();
        }
    }

    private void encodeImagetoString() {
        new AsyncTask<Void, Void, String>() {
            protected void onPreExecute() {

            };

            @Override
            protected String doInBackground(Void... params) {
                BitmapFactory.Options options = null;
                options = new BitmapFactory.Options();
                options.inSampleSize = 3;
                bitmap = BitmapFactory.decodeFile(imgPath,
                        options);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                // 压缩图片
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
                byte[] byte_arr = stream.toByteArray();
                // Base64图片转码为String
                encodedString = Base64.encodeToString(byte_arr, 0);
                return "";
            }

            @Override
            protected void onPostExecute(String msg) {
              //  prgDialog.setMessage("Calling Upload");
                // 将转换后的图片添加到上传的参数中
                params.put("image", encodedString);
               // params.put("filename", editTextName.getText().toString());
                // 上传图片
                imageUpload();
            }
        }.execute(null, null, null);
    }

    public void imageUpload() {
        //prgDialog.setMessage("Invoking JSP");
//        String url = "http://106.14.221.71:8080/Service_dlz/uploadimg.jsp";
//        AsyncHttpClient client = new AsyncHttpClient();
//        client.post(url, params, new AsyncHttpResponseHandler() {
//
//            @Override
//            public void onSuccess(int i, org.apache.http.Header[] headers, byte[] bytes) {
//                Log.d("上传成功", String.valueOf(bytes));
//            }
//
//            @Override
//            public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] bytes, Throwable throwable) {
//                Log.d("上传失败", "onSuccess: ");
//                if (statusCode == 404) {
//                    Toast.makeText(getApplicationContext(),
//                            "Requested resource not found", Toast.LENGTH_LONG).show();
//                }
//                // 当 Http 响应码'500'
//                else if (statusCode == 500) {
//                    Toast.makeText(getApplicationContext(),
//                            "Something went wrong at server end", Toast.LENGTH_LONG).show();
//                }
//                // 当 Http 响应码 404, 500
//                else {
//                    Toast.makeText(
//                            getApplicationContext(), "Error Occured n Most Common Error: n1. Device " +
//                                    "not connected to Internetn2. Web App is not deployed in App servern3." +
//                                    " App server is not runningn HTTP Status code : "
//                                    + statusCode, Toast.LENGTH_LONG).show();
//                }
//            }
//        });


//        //okHttp请求
//        Log.d("data:",encodedString);
        String url = "http://106.14.221.71:8080/Service_dlz/release_save.action";
        Map map=new HashMap();
        SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);

        content=editTextName.getText().toString();
        map.put("re_image",encodedString);
        map.put("re_content",content);
        map.put("re_username",sp.getString("currentUsername",""));
        HttpUtil.postDataAsyn(url, map, new MyNetCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                Log.d("看一下有没有内容：", content+"qqqqq");
                Log.d("提交成功", "success: ");

            }

            @Override
            public void failed(Call call, IOException e) {
                Log.d("提交失败", "success: ");
            }
        });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (prgDialog != null) {
            prgDialog .dismiss();
        }
    }

}
